package com.aiyige.page.my.settings.acount;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.eventbus.EventChangePhoneNumberSuccess;
import com.aiyige.model.ThirdOauthModel;
import com.aiyige.model.User;
import com.aiyige.model.request.LoginOtherRequest;
import com.aiyige.model.response.ErrorResponse;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ShareUtil;
import com.aiyige.utils.ToastX;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.vondear.rxtools.RxEncodeTool;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.nio.charset.Charset;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 账号与安全
 * xiachao
 */
@Route(path = ARouterConfig.AccountPage, extras = ARouterConfig.EXTRA_NEED_LOGIN)
public class AccountPage extends BaseActivity {

    private final static int WECHAT = 1;

    private final static int QQ = 2;

    private final static int WEIBO = 3;

    @BindView(R.id.tv_mobile)
    TextView tvMobile;

    User.MoreBackup moreBackup;
    @BindView(R.id.tv_weixin_banding_status)
    TextView tvWeixinBandingStatus;
    @BindView(R.id.tv_qq_banding_status)
    TextView tvQqBandingStatus;
    @BindView(R.id.tv_weibo_banding_status)
    TextView tvWeiboBandingStatus;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_account);
        ButterKnife.bind(this);
        initTitleLayout(getString(R.string.menu_setting_account_safety));
        fillViews();
        setAutoRegisterEventBus(true);
    }


    private void fillViews() {
        String mobile = AccountUtil.getMobile() == null ? "" : AccountUtil.getMobile();
        tvMobile.setText(mobile);
        moreBackup = AccountUtil.getCurrentUser() != null ? AccountUtil.getCurrentUser().getMoreBackup() : null;
        if (moreBackup != null) {
            tvWeixinBandingStatus.setText(getResources().getString(moreBackup.isBindWeixin() ? R.string.untie : R.string.banding));
            tvQqBandingStatus.setText(getResources().getString(moreBackup.isBindQQ() ? R.string.untie : R.string.banding));
            tvWeiboBandingStatus.setText(getResources().getString(moreBackup.isBindSina() ? R.string.untie : R.string.banding));
            tvWeixinBandingStatus.setSelected(!moreBackup.isBindWeixin());
            tvQqBandingStatus.setSelected(!moreBackup.isBindQQ());
            tvWeiboBandingStatus.setSelected(!moreBackup.isBindSina());
        }
    }


    @OnClick({R.id.settings_change_mobile_layout, R.id.settings_change_password_layout, R.id.settings_change_wallet_password_layout, R.id.settings_weixin, R.id.settings_qq, R.id.settings_weibo})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.settings_change_mobile_layout:
                ARouter.getInstance().build(ARouterConfig.ChangePhoneNumberVerifyPage).navigation();
                break;
            case R.id.settings_change_password_layout:
                ARouter.getInstance().build(ARouterConfig.ChangePasswordVerifyPage).navigation();
                break;
            case R.id.settings_change_wallet_password_layout:
                ARouter.getInstance().build(ARouterConfig.ChangeWalletPasswordVerifyCodePage).navigation();
                break;
            case R.id.settings_weixin:
                if (moreBackup.isBindWeixin()) {
                    unBinding(WECHAT);
                } else {
                    binding(WECHAT);
                }
                break;
            case R.id.settings_qq:
                if (moreBackup.isBindQQ()) {
                    unBinding(QQ);
                } else {
                    binding(QQ);
                }
                break;
            case R.id.settings_weibo:
                if (moreBackup.isBindSina()) {
                    unBinding(WEIBO);
                } else {
                    binding(WEIBO);
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onChangeSuccessEventBuss(EventChangePhoneNumberSuccess eventChangePhoneNumberSuccess) {
        if (eventChangePhoneNumberSuccess != null) {
            fillViews();
        }
    }


    private SHARE_MEDIA getResourceType(String resource) {
        if (resource.equals(ThirdOauthModel.SOURCE_QQ)) {
            return SHARE_MEDIA.QQ;
        }
        if (resource.equals(ThirdOauthModel.SOURCE_SINA)) {
            return SHARE_MEDIA.SINA;
        }
        if (resource.equals(ThirdOauthModel.SOURCE_WEIXIN)) {
            return SHARE_MEDIA.WEIXIN;
        }
        return null;
    }


    private void requestBind(final String resource) {
        if (resource.contains(ThirdOauthModel.SOURCE_WEIXIN) && !ShareUtil.isWeixinAvilible()) {
            ToastX.show(MyApp.getAppContext().getString(R.string.weixin_not_install));
            return;
        }
        UMShareAPI mShareAPI = UMShareAPI.get(this);
        mShareAPI.getPlatformInfo(this, getResourceType(resource), new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                String source = "";
                int type = 0;
                if (share_media == SHARE_MEDIA.WEIXIN) {
                    type = 3;
                    source = ThirdOauthModel.SOURCE_WEIXIN;
                } else if (share_media == SHARE_MEDIA.QQ) {
                    type = 1;
                    source = ThirdOauthModel.SOURCE_QQ;
                } else if (share_media == SHARE_MEDIA.SINA) {
                    type = 2;
                    source = ThirdOauthModel.SOURCE_SINA;
                }
                LoginOtherRequest loginOtherRequest = LoginOtherRequest.newBuilder()
                        .accessToken(map.get(type == 2 ? "accessToken" : "access_token"))
                        .avatar(map.get("iconurl"))
                        .nickName(RxEncodeTool.base64Encode2String(map.get("name").getBytes(Charset.forName("UTF-8"))))
                        .openid(map.get("openid"))
                        .province(map.get("province"))
                        .sex(map.get("gender"))
                        .type(type)
                        .uid(map.get("uid"))
                        .city(map.get(type == 2 ? "location" : "city"))
                        .country(map.get("country"))
                        .build();
                Log.i("xcLogin", loginOtherRequest.toString());
                ThirdOauthModel thirdOauthModel = ThirdOauthModel.newBuilder().accessToken(loginOtherRequest.getAccessToken())
                        .avatar(loginOtherRequest.getAvatar())
                        .nickName(loginOtherRequest.getNickName())
                        .openid(loginOtherRequest.getOpenid())
                        .source(source)
                        .uid(loginOtherRequest.getUid())
                        .build();
                //调用服务器接口
                ApiManager.getService().bindThirdOauth(thirdOauthModel).enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(final Call<ResponseBody> call, final Response<ResponseBody> response) {
                        try {
                            if (response.isSuccessful()) {
                                if (resource.equals(ThirdOauthModel.SOURCE_QQ)) {
                                    moreBackup.setBindQQ(true);
                                } else if (resource.equals(ThirdOauthModel.SOURCE_WEIXIN)) {
                                    moreBackup.setBindWeixin(true);
                                } else if (resource.equals(ThirdOauthModel.SOURCE_SINA)) {
                                    moreBackup.setBindSina(true);
                                }
                                ToastX.show(getString(R.string.binding_success));
                                User user = AccountUtil.getCurrentUser();
                                user.setMoreBackup(moreBackup);
                                AccountUtil.updateCurrentUser(user);
                                fillViews();
                            } else {
                                ErrorResponse data = JsonUtil.toObject(response.errorBody().string(), ErrorResponse.class);
                                onFailure(call, new Throwable(data.getMessage()));
                            }
                        } catch (Exception e) {
                            try {
                                onFailure(call, new Throwable(e.toString()));
                            } catch (Exception e1) {
                                e1.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        if (t != null) {
                            ToastX.show(t.getMessage());
                        }
                    }
                });

            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                ToastX.show(throwable.getMessage());
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                ToastX.show(MyApp.getAppContext().getString(R.string.authorization_failed_please_try_again));
            }
        });
    }


    private void requestUnbind(final String resource) {
        ApiManager.getService().unbindThirdOauth(ThirdOauthModel.newBuilder().source(resource).build()).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(final Call<ResponseBody> call, final Response<ResponseBody> response) {
                try {
                    if (response.isSuccessful()) {
                        if (resource.equals(ThirdOauthModel.SOURCE_QQ)) {
                            moreBackup.setBindQQ(false);
                        } else if (resource.equals(ThirdOauthModel.SOURCE_WEIXIN)) {
                            moreBackup.setBindWeixin(false);
                        } else if (resource.equals(ThirdOauthModel.SOURCE_SINA)) {
                            moreBackup.setBindSina(false);
                        }
                        ToastX.show(getString(R.string.unbinding_success));
                        User user = AccountUtil.getCurrentUser();
                        user.setMoreBackup(moreBackup);
                        AccountUtil.updateCurrentUser(user);
                        fillViews();
                    } else {
                        ErrorResponse data = JsonUtil.toObject(response.errorBody().string(), ErrorResponse.class);
                        onFailure(call, new Throwable(data.getMessage()));
                    }
                } catch (Exception e) {
                    try {
                        onFailure(call, new Throwable(e.toString()));
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                if (t != null) {
                    ToastX.show(t.getMessage());
                }
            }
        });
    }


    /**
     * 绑定
     *
     * @param type
     */
    private void binding(int type) {
        String resource = "";
        switch (type) {
            case WECHAT: {
                resource = ThirdOauthModel.SOURCE_WEIXIN;
                break;
            }
            case QQ: {
                resource = ThirdOauthModel.SOURCE_QQ;
                break;
            }
            case WEIBO: {
                resource = ThirdOauthModel.SOURCE_SINA;
                break;
            }
        }
        requestBind(resource);
    }

    /**
     * 解绑
     *
     * @param type
     */
    private void unBinding(final int type) {
        String name = null;
        switch (type) {
            case WECHAT: {
                name = getResources().getString(R.string.weixin);
                break;
            }
            case QQ: {
                name = "QQ";
                break;
            }
            case WEIBO: {
                name = getResources().getString(R.string.weibo);
                break;
            }
        }
        new AlertDialog.Builder(this).setTitle(getString(R.string.alert_unbinding, name))
                .setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String resource = null;
                        switch (type) {
                            case WECHAT: {
                                resource = ThirdOauthModel.SOURCE_WEIXIN;
                                break;
                            }
                            case QQ: {
                                resource = ThirdOauthModel.SOURCE_QQ;
                                break;
                            }
                            case WEIBO: {
                                resource = ThirdOauthModel.SOURCE_SINA;
                                break;
                            }
                        }
                        requestUnbind(resource);
                        dialog.dismiss();
                    }
                }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();
    }


}
